package com.ssamkj.wstar.common;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class CommonUtil {
	private static final Logger log = LoggerFactory
			.getLogger(CommonUtil.class);

	@SuppressWarnings("unchecked")
	public static Entry<String, String> extracted(Iterator<?> iterator) {
		return (Map.Entry<String, String>) iterator.next();
	}

	public static void viewMap(Map<?, ?> map) {
		log.debug("#####################################################");
		Iterator<?> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, String> pairs = extracted(iterator);
			if (log.isDebugEnabled()) {
				log.debug("----------------------------------");
				log.debug("key : " + pairs.getKey() + ", value : "
						+ pairs.getValue());
				log.debug("----------------------------------");
			}
		}
		log.debug("#####################################################");
	}

	public static String getTargetString(Map<?, ?> paramMap, String target) {
		String result = null;
		if (paramMap.containsKey(target) && StringUtils.hasLength(target)) {
			result = paramMap.get(target).toString();
			// Assert.notNull(result, target + " is Null!!");
		}
		return result;
	}

	@SuppressWarnings("deprecation")
	public static String decode(String _str) {
		try {
			return URLDecoder.decode(_str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.debug("##### decode UnsupportedEncodingException #####");
		}
		return URLDecoder.decode(_str);
	}

	/**
	 * 특정 KEY를 연속으로 갖는 MAP에서 VALUE 축출하기.<BR/>
	 * EX)<br/>
	 * getListFromMap("list", paramMap)<br/>
	 * paramMap = {"list0":"1",<br/>
	 * "list1":"2",<br/>
	 * "list2":"3",<br/>
	 * "list3":"4"}<br/>
	 * <br/>
	 * return 값은 List에 1,2,3,4 가 들어간 값 이다.<br/>
	 * 
	 * @param name
	 * @param map
	 * @return
	 */
	public static List<String> getListFromMap(String name, Map<?, ?> map) {
		log.debug("getListFromMap name=" + name);
		Iterator<?> it = map.entrySet().iterator();
		List<String> list = new ArrayList<String>();
		while (it.hasNext()) {
			Map.Entry<String, String> pairs = extracted(it);
			if (pairs.getKey().contains(name)) {
				list.add(pairs.getValue());
			}
		}
		return list;
	}
}
